package danran.other;

import danran.ListNode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Classname SplitListToParts
 * @Description TODO
 * @Date 2021/9/22 9:05
 * @Created by ASUS
 */
public class SplitListToParts {
    public ListNode[] splitListToParts(ListNode head, int k) {
        List<ListNode> nodes = traverseList(head).stream().map(node -> new ListNode(node.val)).collect(Collectors.toList());
        int seq_length = nodes.size() / k;
        if (seq_length == 0) {
            return nodes.toArray(new ListNode[k]);
        }
        int yu = nodes.size() % k;
        List<ListNode> ans = new ArrayList<>();
        int index = -seq_length;
        for (int i = 0; i < k; i++) {
            if (yu != 0 &&i != 0) {
                index = index + seq_length + 1;
                yu--;
            } else index += seq_length;
            ans.add(nodes.get(index));
        }
        Queue<ListNode> q = new ArrayDeque<>(nodes);
        for (int i = 0; i < ans.size(); i++) {
            ListNode cur = ans.get(i), next_head = (i + 1 == ans.size()) ? null : ans.get(i + 1);
            while (cur != next_head && cur != null) {
                ListNode poll = q.poll();
                if (poll == cur) continue;
                if (poll == next_head) poll = null;
                cur.next = poll;
                cur = poll;
            }
        }
        return ans.toArray(new ListNode[k]);
    }

    public List<ListNode> traverseList(ListNode head) {
        List<ListNode> array = new ArrayList<>();
        ListNode cur = head;
        while (cur != null) {
            array.add(cur);
            cur = cur.next;
        }
        return array;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, null)));
        ListNode[] listNodes = new SplitListToParts().splitListToParts(head, 5);
        Arrays.stream(listNodes).forEach(node -> System.out.println(node.val));
    }
}
